package com.heatup.apt.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;


public class MD5 {

    //log
    private static final Logger log = LoggerFactory.getLogger(MD5.class);

    private MD5() {
    }


    public final static String getMessageDigest(byte[] buffer) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(buffer);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            log.error("MD5生成时出错----> " + e.getMessage() + e.toString());
            return null;
        }
    }

    /**
     * 获取一个加密的MD5字符串
     * 加密规则：去空格MD5加密以后转大写
     * SysUserUtil.getMD5String()<BR>
     * <P>Author :  fangxiaowen </P>
     * <P>Date : 2016年10月14日 </P>
     *
     * @param string
     * @return
     */
    public static String getMD5String(String string) {
        return MD5.getMessageDigest(string.toString().trim().getBytes()).toUpperCase();
    }


}
